package com.erp.utils;

import com.alibaba.fastjson.JSONObject;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DataBaseUtils {

    public static List<JSONObject> getQueryMap(Connection conn, String querySql) throws SQLException {
        List<JSONObject> list = new ArrayList<>();
        PreparedStatement rst = conn.prepareStatement(querySql);
        ResultSet data = rst.executeQuery();
        ResultSetMetaData rood = data.getMetaData();
        int fieldCount = rood.getColumnCount();

        while (data.next()) {
            JSONObject valueMap = new JSONObject();
            for (int i = 1; i <= fieldCount; i++) {
                String name = rood.getColumnLabel(i);//获取的别名  真正列名getColumnName
                String value = data.getString(name);
                valueMap.put(name, value);
            }
            list.add(valueMap);
        }
        return list;
    }

    public static Connection getConnection(String dataBase) throws ClassNotFoundException, SQLException {
        return getConnection("127.0.0.1", "3306", dataBase);
    }

    public static Connection getConnection(String ip, String port, String dataBase) throws ClassNotFoundException, SQLException {
        return getConnection(ip, port, dataBase, "root", "root");
    }

    public static Connection getConnection(String ip, String port, String dataBase, String user, String password) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");// mysql
        String url = "jdbc:mysql://" + ip + ":" + port + "/" + dataBase + "?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useOldAliasMetadataBehavior=true&tinyInt1isBit=false";
        return DriverManager.getConnection(url, user, password);
    }
}
